package com.yiwu.common.utils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.yiwu.common.enums.ResponseCode;
import com.yiwu.common.exception.BusinessException;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;

/**
 * @version 1.0
 * @description TODO
 * @date 2024/5/26 18:08
 */
public class EncryptionUtil {

    private static final byte[] key = "1hkdw67i90a1c5ef".getBytes(CharsetUtil.CHARSET_UTF_8);

    public static SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

    public static String encrypt(String content){
        //加密为16进制表示
        return aes.encryptHex(content);
    }


    public static String decrypt(String content){
        //解密为字符串
        return aes.decryptStr(content, CharsetUtil.CHARSET_UTF_8);
    }

    public static Long getUserToken(HttpServletRequest request){
        String authHeader = request.getHeader("Authorization");
        if(StringUtils.isEmpty(authHeader)) throw new BusinessException(ResponseCode.NO_LOGIN);
        return Long.parseLong(EncryptionUtil.decrypt(authHeader));
    }

}
